package com.zz.controller;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.sun.org.apache.bcel.internal.classfile.Constant;
import com.zz.domain.User;
import com.zz.dto.LoginToken;
import com.zz.dto.ResponseResult;
import com.zz.exception.UserException;
import com.zz.services.UserService;
import com.zz.util.Constants;
import com.zz.util.VideoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    //退出登录
    @RequestMapping("logout")
    public String logout(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        //清空用户session
        session.removeAttribute("login_user");

        String token =  VideoUtil.getCookieTokenValue(request.getCookies());
        Boolean valid = VideoUtil.checkLoginToken(token,request);
        if (valid){
            HashMap<String,LoginToken> tokenMap = ( HashMap<String,LoginToken>) request.getServletContext().getAttribute(Constants.AUTO_LOGIN_TOKEN);
            tokenMap.remove(token);
        }
        Cookie cookie = new Cookie(Constants.COOKIE_TOKEN_KEY,"");
        cookie.setMaxAge(1);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:/";
    }

    //登录前验证一遍email和password
    @RequestMapping("checkLogin")
    @ResponseBody
    public ResponseResult checkLogin(User user){
        ResponseResult rr = new ResponseResult(-1,"账户名或密码错误");
        User user1 =  userService.login(user);
        if (user1 != null){
            rr.setRcode(1);
            rr.setMessage("ok");
        }
        return  rr;
    }

    @RequestMapping(path = "login",method = {RequestMethod.POST})
    public String login(User user, String autoLogin, HttpSession session,  HttpServletRequest req, HttpServletResponse response){
        System.out.println("autoLogin:" +autoLogin);
        if ( StrUtil.isEmpty(user.getPassword()) || StrUtil.isEmpty(user.getEmail()) ){
            throw new UserException("账户名或密码不正确");
        }
        User user1 =  userService.login(user);
        System.out.println(user1);
        if (user1 != null){
            session.setAttribute(Constants.SESSION_LOGIN_USER,user); //把找到的user对象存到session
            if( !StrUtil.isEmpty(autoLogin) && "1".equals(autoLogin) ){
                //获取全局上下文对象
                ServletContext application = req.getServletContext();
                //做自动登录  需要ip,浏览器userAgent,user.email,创建时间
                LoginToken loginToken =  VideoUtil.generateLoginToken(req,user);
                //生成自动登录凭证
                String token =  loginToken.generateToken();
                //所有的凭证为键,LoginToken对象是值
                HashMap<String,LoginToken>   loginTokenMap = (HashMap<String,LoginToken>) application.getAttribute(Constants.AUTO_LOGIN_TOKEN);

                if (loginTokenMap == null){
                    //如果是空,就重新创建
                    loginTokenMap = new HashMap<>();
                    loginTokenMap.put(token,loginToken);
                    application.setAttribute(Constants.AUTO_LOGIN_TOKEN,loginTokenMap);
                }else{
                    loginTokenMap.put(token,loginToken);
                }
                Cookie cookie = new Cookie("autoLogin",token);
                cookie.setPath("/");
                cookie.setMaxAge(60*60*48);
                response.addCookie(cookie);
            }
        }
        
        return  "redirect:/";
    }

    //验证email有没有被使用
    @RequestMapping("/checkEmail")
    @ResponseBody
    public ResponseResult checkEmail(String email){
        ResponseResult rr = new ResponseResult(-1,"email已被注册");
        User user = userService.existEmail(email);
        if (user == null){
            rr.setRcode(1);
            rr.setMessage("email可以使用");
        }
        return  rr;
    }

    @RequestMapping("/regist")
    public String regist(User user, HttpServletRequest req,String vcode){
        HttpSession session =  req.getSession(true);
        String sVcode  = (String) session.getAttribute("session_vcode");
        if (StrUtil.isEmpty(vcode) || StrUtil.isEmpty(sVcode)){
            throw new UserException("验证码未填写");
        }
        if (!sVcode.equals(vcode)){
            throw new UserException("验证码不正确");
        }
        boolean emailMatch = ReUtil.isMatch("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", user.getEmail());
        boolean phoneMatch = ReUtil.isMatch("1[3456789]\\d{9}$", user.getMobile());
        boolean passwordMatch = ReUtil.isMatch("^(?![\\d]+$)(?![a-zA-Z]+$)(?![^\\da-zA-Z]+$).{6,20}$", user.getPassword());
        System.out.println(emailMatch);
        System.out.println(phoneMatch);
        System.out.println(passwordMatch);
        if (!phoneMatch || !emailMatch || !passwordMatch){
            throw new UserException("注册信息错误");
        }
        int code = userService.register(user);
        if (code !=1 ){
            throw new UserException("用户创建失败");
        }
        session.setAttribute("login_user",user);
        return "redirect:/";
    }
}
